package umputun.jutw.utils.common;

import java.util.Random;

/*
 Copyright 2009 Umputun

 This file is part of JUTW.

 JUTW is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 JUTW is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with JUTW.  If not, see http://www.gnu.org/licenses/.
*/


public class EasyCipher {

	public EasyCipher(String key) {
		this.key = key;
	}

	public String encrypt(String text) {

		long final_key = 0;

		for (int i=0; i<key.length(); i++) {
			long tmp_key = key.charAt(i);
			tmp_key *= 128;
			final_key += tmp_key;
		}

		Random generator = new Random(final_key);
		String result = "";
		for (int i=0; i<text.length(); i++)	{
			int temp = text.charAt(i);
			temp += generator.nextInt(95);
			if (temp > 126) temp -= 95;
			result += (char)temp;
		}

		return result;
	}

	public String decrypt(String text) {

		long final_key = 0;
		for (int i=0; i<key.length(); i++) {
			long tmp_key = key.charAt(i);
			tmp_key *= 128;
			final_key += tmp_key;
		}

		Random generator = new Random(final_key);
		String result = "";
		for (int i=0; i<text.length(); i++)
		{
			int temp = text.charAt(i);
			temp -= generator.nextInt(95);
			if (temp < 36) temp+= 95;
			else
				if (temp > 126) temp -= 95;
			result += (char)temp;
		}
		return result;
	}

	private final String key;
}
